
// 236.二叉树的最近公共祖先
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    bool dfs(TreeNode* cur , TreeNode* tar)
    {
        if(cur == nullptr) return false;
        if(cur == tar) return true;
        if(dfs(cur->left , tar) || dfs(cur->right , tar)) return true;
        return false;
    };
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == p || root == q) return root;
        bool pl = dfs(root->left , p) , ql = dfs(root->left , q);
        bool pr = !pl , qr = !ql;
        if((pl && qr) || (pr && ql)) return root;
        if(pl && ql) return lowestCommonAncestor(root->left , p , q);
        else  return lowestCommonAncestor(root->right , p , q);
    }
};